<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Sms as Smslib;
use app\common\model\Area;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 入驻审批管理
 *
 * @icon fa fa-circle-o
 */
class Auditlog extends Backend
{

    /**
     * Auditlog模型对象
     * @var \app\admin\model\\Auditlog
     */
    protected $model = null;
    protected $searchFields = 'name,phone';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Auditlog;
        $this->view->assign("roleList", $this->model->getRoleList());
        $this->view->assign("auditStatusList", $this->model->getAuditStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }



            $filter = json_decode($this->request->get("filter", ''), true);
            $op = json_decode($this->request->get("op", '', 'trim'), true);
            // 如果存在 realname，进行相关处理
            if (isset($filter['role_text'])) {
                $filter['role']=$filter['role_text'];
                unset($filter['role_text'], $op['role_text']);

            }


            // 更新请求参数
            $this->request->get(['filter' => json_encode($filter, true)]);
            $this->request->get(['op' => json_encode($op, true)]);

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user','admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $provinceName = Area::where('id', $row['province'])->value('name');
                $cityName = Area::where('id',$row['city'] )->value('name');
                $districtName = Area::where('id', $row['district'])->value('name');
//                $row->addr=$provinceName.$cityName.$districtName.$row->addr;
                if($row->audit_time){
                    $row->audit_time  = date('Y-m-d H:i:s', $row->audit_time);
                }
                if($row->applicant_id!=null){
                   $applicant=\app\admin\model\Details::where('user_id','=',$row->applicant_id)->find();
                   if($applicant){
                       $row->applicant='上级/'.$applicant['name'];
                   }else{
                       $row->applicant='-';
                   }

                }else{
                    $row->applicant='本人';
                }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        $params['auditor'] = $this->auth->id;
        $params['audit_time'] = time();

        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if($params['audit_status']=='已审核'){
                //判断手机号存不存在
                unset($params['audit_time']);
                unset($params['auditor']);
                unset($params['audit_status']);
                unset($params['audit_comments']);
                if($row['user_id']!=0&&$row['user_id']!=null){
                    $params['user_id']=$row['user_id'];
                }
                $params['applicant_id']=$row['applicant_id'];
                $params['signature_url']=$row['signature_url'];
                $params['latitude']=$row['latitude'];
                $params['longitude']=$row['longitude'];
                //审核成功 同步到用户信息表
                if(isset($params['user_id'])){
                    $phone=\app\admin\model\Details::where('phone','=',$params['phone'])->where('user_id','<>',$params['user_id'])->find();
                    if($phone){
                        $this->error(__('此手机号已申请过'));
                    }
                    $pd=\app\admin\model\Details::where(['user_id'=>$params['user_id'],'role'=>$params['role']])->find();
                    if ($pd) {
                        \app\admin\model\Details::where('id',$pd['id'])->update($params);
                    }else{
                        \app\admin\model\Details::create($params);
                    }
                    \app\admin\model\User::where('id',$params['user_id'])->update(['role'=>$params['role']]);
                }else{
                    $phone=\app\admin\model\Details::where('phone','=',$params['phone'])->find();
                    if($phone){
                        $this->error(__('此手机号已申请过'));
                    }
                    \app\admin\model\Details::create($params);
                }

                $ret = Smslib::send($params['phone'], null, 'PayOrder');

            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

}
